<template>
    <view class="search-page">
        <!-- 搜索头部 -->
        <view class="status-bar" :style="{ height: `${systemInfo?.statusBarHeight}px` }" />
        <view class="search-header">
            <view class="search-bar" :style="searchBarStyle">
                <view class="back-btn" @click="goBack">
                    <wd-icon name="arrow-left" size="18" />
                </view>
                <view class="search-input-wrap">
                    <wd-search
                        v-model="searchValue"
                        placeholder="搜索商品"
                        :focus="true"
                        :cancel-text="''"
                        @search="handleSearch"
                    />
                    <!-- 将操作按钮放在搜索框外部 -->
                    <view class="search-actions">
                        <wd-icon 
                            v-if="searchValue"
                            name="close-fill" 
                            size="16" 
                            class="clear-icon"
                            @click.stop="searchValue = ''"
                        />
                        <view class="search-btn" @click="handleSearch">
                            搜索
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 搜索内容区域 -->
        <scroll-view scroll-y class="search-content">
            <!-- 搜索发现 -->
            <view class="search-section" v-if="!searchValue">
                <view class="section-header">
                    <text class="title">搜索发现</text>
                </view>
                <view class="hot-keywords">
                    <view 
                        class="keyword-tag"
                        v-for="item in hotKeywords"
                        :key="item.id"
                        @click="quickSearch(item.keyword)"
                    >
                        {{ item.keyword }}
                    </view>
                </view>
            </view>

            <!-- 搜索历史 -->
            <view class="search-section" v-if="!searchValue && searchHistory.length > 0">
                <view class="section-header">
                    <text class="title">搜索历史</text>
                    <view class="clear-btn" @click="clearHistory">
                        <wd-icon name="delete" size="16" />
                        <text>清空历史</text>
                    </view>
                </view>
                <view class="history-list">
                    <view 
                        class="history-item"
                        v-for="(item, index) in searchHistory"
                        :key="index"
                        @click="quickSearch(item)"
                    >
                        <wd-icon name="search" size="14" />
                        <text class="keyword">{{ item }}</text>
                        <wd-icon 
                            name="close" 
                            size="14" 
                            @click.stop="removeHistoryItem(index)"
                        />
                    </view>
                </view>
            </view>

            <!-- 搜索建议 -->
            <view class="search-suggestions" v-if="searchValue && suggestions.length > 0">
                <view 
                    class="suggestion-item"
                    v-for="item in suggestions"
                    :key="item.id"
                    @click="quickSearch(item.keyword)"
                >
                    <wd-icon name="search" size="14" />
                    <text>{{ item.keyword }}</text>
                </view>
            </view>
        </scroll-view>
    </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getSystemInfo } from '@/utils/system'

// 系统信息
const systemInfo = ref(null)

// 搜索相关
const searchValue = ref('')
const searchHistory = ref([])

// 热门搜索词
const hotKeywords = ref([
    { id: 1, keyword: '空调' },
    { id: 2, keyword: '冰箱' },
    { id: 3, keyword: '洗衣机' },
    { id: 4, keyword: '电视' },
    { id: 5, keyword: '热水器' },
    { id: 6, keyword: '油烟机' },
    { id: 7, keyword: '电饭煲' },
    { id: 8, keyword: '微波炉' }
])

// 搜索建议
const suggestions = ref([])

// 获取本地存储的搜索历史
const getLocalHistory = () => {
    try {
        const history = uni.getStorageSync('searchHistory')
        if (history) {
            searchHistory.value = JSON.parse(history)
        }
    } catch (e) {
        console.error('获取搜索历史失败:', e)
    }
}

// 保存搜索历史到本地
const saveHistory = (keyword) => {
    if (!keyword) return
    
    // 移除重复项
    const index = searchHistory.value.indexOf(keyword)
    if (index !== -1) {
        searchHistory.value.splice(index, 1)
    }
    
    // 添加到开头
    searchHistory.value.unshift(keyword)
    
    // 限制历史记录数量
    if (searchHistory.value.length > 10) {
        searchHistory.value.pop()
    }
    
    // 保存到本地
    try {
        uni.setStorageSync('searchHistory', JSON.stringify(searchHistory.value))
    } catch (e) {
        console.error('保存搜索历史失败:', e)
    }
}

// 清空搜索历史
const clearHistory = () => {
    uni.showModal({
        title: '提示',
        content: '确定要清空搜索历史吗？',
        success: (res) => {
            if (res.confirm) {
                searchHistory.value = []
                uni.setStorageSync('searchHistory', '[]')
            }
        }
    })
}

// 移除单个历史记录
const removeHistoryItem = (index) => {
    searchHistory.value.splice(index, 1)
    uni.setStorageSync('searchHistory', JSON.stringify(searchHistory.value))
}

// 快速搜索
const quickSearch = (keyword) => {
    searchValue.value = keyword
    handleSearch()
}

// 添加计算搜索栏样式
const searchBarStyle = computed(() => {
    if (!systemInfo.value?.menuButtonRect) return {}
    
    const { menuButtonRect } = systemInfo.value
    return {
        position: 'fixed',
        top: `${menuButtonRect.top}px`,
        left: '24rpx',
        height: `${menuButtonRect.height}px`,
        width: `${menuButtonRect.left - 24}px`,
        zIndex: 100
    }
})

// 修改处理搜索方法
const handleSearch = () => {
    if (!searchValue.value.trim()) return
    
    // 保存搜索历史
    saveHistory(searchValue.value.trim())
    
    // 跳转到商品列表页并传递搜索参数
    uni.navigateTo({
        url: `/pages/goods/list?fullQuery=${encodeURIComponent(searchValue.value.trim())}`
    })
}

// 添加返回方法
const goBack = () => {
    uni.navigateBack()
}

// 页面加载
onMounted(() => {
    systemInfo.value = getSystemInfo()
    getLocalHistory()
})
</script>

<style lang="scss" scoped>
.search-page {
    min-height: 100vh;
    background: #fff;
}

.status-bar {
    background: #fff;
    width: 100%;
    flex-shrink: 0;
}

.search-header {
    position: relative;
    z-index: 1;
    background: #fff;
    flex-shrink: 0;
    padding-top: v-bind('(systemInfo?.menuButtonRect?.height || 0) + (systemInfo?.menuButtonRect?.top || 0) - (systemInfo?.statusBarHeight || 0) + "px"');
}

.search-bar {
    background: #fff;
    box-sizing: border-box;
    display: flex;
    align-items: center;

    .back-btn {
        padding: 0 20rpx;
        height: 100%;
        display: flex;
        align-items: center;
        color: #333;
        
        &:active {
            opacity: 0.8;
        }
    }

    .search-input-wrap {
        flex: 1;
        display: flex;
        align-items: center;
        background-color: #f5f5f5;
        border-radius: 32rpx;
        margin-right: 20rpx;
        padding-right: 20rpx;
    }

    :deep(.wd-search) {
        flex: 1;
        height: 100%;
        padding: 0;
        background: transparent;
        
        .wd-search__inner {
            background: transparent;
            margin: 0;
            padding: 0 20rpx;
        }

        // 隐藏默认的取消按钮
        .wd-search__cancel {
            display: none !important;
        }
    }

    .search-actions {
        display: flex;
        align-items: center;
        gap: 12rpx;
    }

    .clear-icon {
        color: #999;
        padding: 6rpx;
        
        &:active {
            opacity: 0.8;
        }
    }

    .search-btn {
        font-size: 28rpx;
        color: #0f5aa5;
        white-space: nowrap;
        padding: 16rpx 0;
        
        &:active {
            opacity: 0.8;
        }
    }
}

.search-content {
    height: calc(100vh - var(--window-top) - 88rpx);
}

.search-section {
    padding: 24rpx;
    
    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24rpx;
        
        .title {
            font-size: 30rpx;
            color: #333;
            font-weight: 500;
        }
        
        .clear-btn {
            display: flex;
            align-items: center;
            gap: 4rpx;
            font-size: 24rpx;
            color: #999;
        }
    }
}

.hot-keywords {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    
    .keyword-tag {
        padding: 12rpx 24rpx;
        background: #f7f8fa;
        border-radius: 32rpx;
        font-size: 26rpx;
        color: #666;
        
        &:active {
            opacity: 0.7;
        }
    }
}

.history-list {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
}

.history-item {
    display: flex;
    align-items: center;
    gap: 12rpx;
    padding: 16rpx 0;
    font-size: 28rpx;
    color: #333;
    
    .wd-icon {
        color: #999;
    }
    
    .keyword {
        flex: 1;
    }
    
    &:active {
        background: #f7f8fa;
    }
}

.search-suggestions {
    padding: 0 24rpx;
    
    .suggestion-item {
        display: flex;
        align-items: center;
        gap: 12rpx;
        padding: 24rpx 0;
        font-size: 28rpx;
        color: #333;
        border-bottom: 1rpx solid #f5f5f5;
        
        .wd-icon {
            color: #999;
        }
        
        &:active {
            background: #f7f8fa;
        }
    }
}
</style> 